/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.embed.domain.feign.factory;


import feign.FeignException;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.cshoo.tattoo.embed.domain.feign.DataCenterFeign;
import org.cshoo.tattoo.embed.domain.feign.dto.QuerySingleConfigResp;
import org.cshoo.tattoo.embed.domain.feign.dto.QuerySingleLookupResp;
import org.cshoo.tattoo.embed.domain.feign.dto.QuerySingleMessageResp;
import org.cshoo.tattoo.embed.infra.exception.FrequentCallException;
import org.cshoo.tattoo.embed.infra.exception.NotConfiguredException;
import org.springframework.stereotype.Component;

/**
 * @author 杨翼
 * @since 1.0
 */
@Component
@Slf4j
public class DataCenterFeignFallbackFactory implements FallbackFactory<DataCenterFeign> {

    @Override
    public DataCenterFeign create(Throwable e) {
        return new DataCenterFeign() {
            @Override
            public QuerySingleConfigResp querySingleConfig(String code) throws Exception {
                log.error(e.getMessage(), e);
                if (e instanceof FeignException.InternalServerError) {
                    throw new NotConfiguredException();
                }
                if (e instanceof FeignException.TooManyRequests) {
                    throw new FrequentCallException();
                }
                throw new RuntimeException();
            }

            @Override
            public QuerySingleLookupResp querySingleLookup(String code) throws Exception {
                log.error(e.getMessage(), e);
                if (e instanceof FeignException.InternalServerError) {
                    throw new NotConfiguredException();
                }
                if (e instanceof FeignException.TooManyRequests) {
                    throw new FrequentCallException();
                }
                throw new RuntimeException();
            }

            @Override
            public QuerySingleMessageResp querySingleMessage(String code) throws Exception {
                log.error(e.getMessage(), e);
                if (e instanceof FeignException.InternalServerError) {
                    throw new NotConfiguredException();
                }
                if (e instanceof FeignException.TooManyRequests) {
                    throw new FrequentCallException();
                }
                throw new RuntimeException();
            }
        };
    }

}
